import React from 'react'
import { withRouter } from 'react-router-dom'
import PropTypes from 'prop-types'
import Paper from 'material-ui/Paper';

import { inject, observer } from 'mobx-react'
import { withStyles } from 'material-ui/styles'
import Helmet from 'react-helmet'

import UserStore from '../../stores/user_store'

import Tabs from '../tabs/index'
import UserCollection from './user_collection'
import RecentReplies from './recent_replies'
import RecentTopics from './recent_topics'
import MessageCount from '../message_count/index'
import Message from './message'

import createStyle from './style/style'
import { get } from '../../util/request'
import { userInfo, userCollection } from '../../constant/api'


@inject((stores) => {
  const store = {
    user: stores.user,
  }
  return store
})
@observer
class UserCenter extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      recentTopics: [],
      recentReplies: [],
      user: { },
      collection: [],
    }
  }
  componentWillMount() {
  }
  componentDidMount() {
    this.init()
  }
  componentDidUpdate(preProps) {
    if (preProps.location.pathname !== this.props.location.pathname) {
      this.init()
    }
  }
  onLoad() {
    this.getUserInfo()
    this.getUserCollection()
  }
  // 获得用户的信息
  getUserInfo() {
    const loginName = this.props.match.params.loginName || this.props.user.userInfo.loginName
    const userInfoUrl = `${userInfo}/${loginName}`
    get(userInfoUrl, {}).then((res) => {
      if (res.status === 200 && res.data.success) {
        const { data } = res.data
        const {
          avatar_url,
          create_at,
          githubUsername,
          loginname,
          recent_replies,
          recent_topics,
          score,
        } = data
        const user = {
          avatarUrl: avatar_url,
          createAt: create_at,
          githubUsername,
          loginName: loginname,
          score,
        }
        const recentTopics = recent_topics
        const recentReplies = recent_replies
        this.setState({
          user,
          recentReplies,
          recentTopics,
        })
      }
    }).catch((e) => {
      console.log(e) //eslint-disable-line
    })
  }
  // 获得用户的收藏
  getUserCollection() {
    const loginName = this.props.match.params.loginName || this.props.user.userInfo.loginName
    const userCollectionUrl = `${userCollection}/${loginName}`
    get(userCollectionUrl, {}).then((res) => {
      if (res.status === 200 && res.data.success) {
        const { data } = res.data
        this.setState({
          collection: data,
        })
      }
    }).catch((e) => {
      console.log(e) //eslint-disable-line
    })
  }
  // tab头
  getTableTitle() {
    const tabTitles = ['最近的话题', '最近的回复的话题', '收藏']
    if (this.checkUser()) {
      tabTitles.push('未读消息')
    }
    return tabTitles
  }
  // 获取和用户相关的topic数量
  getCount() {
    const topicsCount = this.state.recentTopics.length
    const repliesCount = this.state.recentReplies.length
    const collectionCount = this.state.collection.length
    return {
      topicsCount,
      repliesCount,
      collectionCount,
    }
  }
  // tab内容
  getTableContent() {
    const { recentTopics, recentReplies, collection } = this.state
    const tabContent = [
      <RecentTopics topics={recentTopics} />,
      <RecentReplies replies={recentReplies} />,
      <UserCollection collection={collection} />,
    ]
    if (this.checkUser) {
      tabContent.push(<Message />)
    }
    return tabContent
  }
  // 页面初始化
  init() {
    if (this.checkUserLogin()) {
      this.onLoad()
    } else {
      this.goLogin()
    }
  }
  // 前往登录页面
  goLogin() {
    const { history } = this.props
    const loginRedirect = `/login/${encodeURIComponent(this.props.location.pathname)}`
    history.push(loginRedirect)
  }

  // 检查用户是否当前登录的用户
  checkUser() {
    const { loginName } = this.props.match.params
    const userLoginName = this.props.user.userInfo.loginName
    return !loginName || loginName === userLoginName
  }
  // 检查当前用户是否处于登录状态
  checkUserLogin() {
    if (this.checkUser() && !this.props.user.userInfo.loginName) {
      return false
    }
    return true
  }
  render() {
    const tabTitles = this.getTableTitle()
    const tabContent = this.getTableContent()
    const {
      classes,
    } = this.props
    // const { userInfo } = user
    const { user } = this.state
    const count = this.getCount()

    return (
      <div className={classes.userCenter}>
        { user.loginName ?
          <Paper className={classes.info}>
            <Helmet>
              <title>{`${user.loginName}-CNode中文社区`}</title>
            </Helmet>
            <img className={classes.avatar} src={user.avatarUrl} alt={user.loginName} />
            <div className={classes.loginName}>
              <span className={classes.user}>{user.loginName}</span>
              <span className={classes.score}>
                积分：<b className={classes.count}>{user.score}</b>
              </span>
            </div>
            <div className={classes.myArticleCount}>
              <span className={classes.item}>
                帖子 <b className={classes.count}>{count.topicsCount}</b>
              </span>
              <span className={classes.item}>
                回复 <b className={classes.count}>{count.repliesCount}</b>
              </span>
              { this.checkUser() ?
                <span className={classes.item}>
                  收藏 <b className={classes.count}>{count.collectionCount}</b>
                </span>
                  :
                null
              }
            </div>
            { this.checkUser() ?
              <MessageCount className={classes.badge} />
                :
              null
            }
          </Paper>
            :
          null
        }
        <Paper className={classes.topics}>
          <Tabs titles={tabTitles} content={tabContent} />
        </Paper>
      </div>
    )
  }
}
export default withRouter(withStyles(createStyle)(UserCenter))
UserCenter.propTypes = {
  classes: PropTypes.objectOf(Object),
  location: PropTypes.objectOf(Object),
  match: PropTypes.objectOf(Object),
  history: PropTypes.objectOf(Object),
  user: PropTypes.instanceOf(UserStore),
}
